package com.example.controller;

import com.example.model.Blog;
import com.example.model.User;
import com.example.service.BlogService;
import com.example.service.UserService;
import com.example.service.impl.BlogServiceImpl;
import com.example.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 管理员控制器
 */
@WebServlet("/admin/*")
public class AdminServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private BlogService blogService = new BlogServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否登录且是管理员
        HttpSession session = request.getSession(false);
        User currentUser = null;
        if (session != null) {
            currentUser = (User) session.getAttribute("user");
        }
        
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            // 如果未登录或不是管理员，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }
        
        switch (pathInfo) {
            case "/":
                showDashboard(request, response);
                break;
            case "/users":
                showUsers(request, response);
                break;
            case "/blogs":
                showBlogs(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/admin/");
                break;
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否登录且是管理员
        HttpSession session = request.getSession(false);
        User currentUser = null;
        if (session != null) {
            currentUser = (User) session.getAttribute("user");
        }
        
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            // 如果未登录或不是管理员，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }
        
        switch (pathInfo) {
            // 这里可以添加POST操作
            default:
                response.sendRedirect(request.getContextPath() + "/admin/");
                break;
        }
    }
    
    /**
     * 显示管理员控制面板
     */
    private void showDashboard(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获取统计数据
        List<User> users = userService.getAllUsers();
        List<Blog> blogs = blogService.getAllBlogs();
        
        int userCount = users.size();
        int blogCount = blogs.size();
        int viewCount = 0;
        
        // 计算总浏览量
        for (Blog blog : blogs) {
            viewCount += blog.getViewCount();
        }
        
        // 获取最新的5篇博客
        List<Blog> recentBlogs = new ArrayList<>();
        int count = 0;
        for (Blog blog : blogs) {
            if (count < 5) {
                recentBlogs.add(blog);
                count++;
            } else {
                break;
            }
        }
        
        request.setAttribute("userCount", userCount);
        request.setAttribute("blogCount", blogCount);
        request.setAttribute("viewCount", viewCount);
        request.setAttribute("recentBlogs", recentBlogs);
        
        request.getRequestDispatcher("/WEB-INF/jsp/admin/index.jsp").forward(request, response);
    }
    
    /**
     * 显示用户管理页面
     */
    private void showUsers(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获取搜索参数
        String search = request.getParameter("search");
        
        // 获取用户列表
        List<User> allUsers = userService.getAllUsers();
        List<User> userList = new ArrayList<>();
        
        if (search != null && !search.trim().isEmpty()) {
            // 过滤符合搜索条件的用户
            search = search.toLowerCase();
            for (User user : allUsers) {
                if (user.getUsername().toLowerCase().contains(search) || 
                    (user.getNickname() != null && user.getNickname().toLowerCase().contains(search)) ||
                    (user.getFullName() != null && user.getFullName().toLowerCase().contains(search))) {
                    userList.add(user);
                }
            }
        } else {
            userList = allUsers;
        }
        
        request.setAttribute("userList", userList);
        request.getRequestDispatcher("/WEB-INF/jsp/admin/users.jsp").forward(request, response);
    }
    
    /**
     * 显示博客管理页面
     */
    private void showBlogs(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获取搜索参数和分类参数
        String search = request.getParameter("search");
        String category = request.getParameter("category");
        
        // 获取博客列表
        List<Blog> allBlogs = blogService.getAllBlogs();
        List<Blog> blogList = new ArrayList<>();
        
        // 提取所有分类
        Set<String> categories = new HashSet<>();
        for (Blog blog : allBlogs) {
            if (blog.getCategory() != null && !blog.getCategory().trim().isEmpty()) {
                categories.add(blog.getCategory());
            }
        }
        
        // 根据搜索条件和分类过滤
        if ((search != null && !search.trim().isEmpty()) || (category != null && !category.trim().isEmpty())) {
            for (Blog blog : allBlogs) {
                boolean matchSearch = true;
                boolean matchCategory = true;
                
                if (search != null && !search.trim().isEmpty()) {
                    search = search.toLowerCase();
                    matchSearch = blog.getTitle().toLowerCase().contains(search) ||
                                 blog.getContent().toLowerCase().contains(search) ||
                                 blog.getAuthorName().toLowerCase().contains(search);
                }
                
                if (category != null && !category.trim().isEmpty()) {
                    matchCategory = category.equals(blog.getCategory());
                }
                
                if (matchSearch && matchCategory) {
                    blogList.add(blog);
                }
            }
        } else {
            blogList = allBlogs;
        }
        
        request.setAttribute("blogList", blogList);
        request.setAttribute("categories", categories);
        request.getRequestDispatcher("/WEB-INF/jsp/admin/blogs.jsp").forward(request, response);
    }
} 